var layers;
var distance = $('[data-video="distance"]')[0];
var local = $('[data-video="local"]')[0];

//初始化
$(function () {
    //初始化SDK
    var resp = RL_YTX.init(appid);
    ;
    if (170002 == resp.code) {
        //缺少必要参数，详情见msg参数
        //用户逻辑处理
        alert("缺少必要参数");
    } else if (174001 == resp.code) {
        //不支持HTML5，关闭页面
        //用户逻辑处理
        alert("不支持HTML5");
    } else if (200 == resp.code) {
        //初始化成功
        alert("初始化成功!");
        //用户逻辑处理
        //判断不支持的功能，屏蔽页面展示
        // var unsupport = obj.unsupport;
        login();
    }
});

//登录
function login() {
    //账号登录参数设置
    var loginBuilder = new RL_YTX.LoginBuilder();
    loginBuilder.setType(1);//登录类型 1账号登录，2voip账号密码登录
    loginBuilder.setUserName(uid);//设置用户名
    loginBuilder.setPwd();//type值为1时，密码可以不赋值
    loginBuilder.setSig(sig);//设置sig
    loginBuilder.setTimestamp(timestamp);//设置时间戳
    //执行用户登录
    RL_YTX.login(loginBuilder, function (obj) {
        //登录成功回调
        RL_YTX.onMsgReceiveListener(function (obj) {
//收到push消息或者离线消息或判断输入状态
//如果obj.msgType==12  判断obj.msgDomainn的值
//obj.msgDomain 0 无输入状态  1 正在输入  2 正在录音
            onMsgReceiveListener(obj);
        });
        //注册群组通知事件监听
        RL_YTX.onNoticeReceiveListener(function (obj) {
            //收到群组通知
        });
        RL_YTX.onConnectStateChangeLisenter(function (obj) {
            //连接状态变更
            // obj.code;//变更状态 1 断开连接 2 重连中 3 重连成功 4 被踢下线 5 断开连接，需重新登录
            // 断线需要人工重连
            if (obj.code == 5) {
                alert("连接断开，需重新登录");
            }
        });

        //接受音视频
          RL_YTX.onCallMsgListener(
               function(obj) {
                   receverVideo(obj);
                   // alert("success")
               });


    }, function (obj) {
        //登录失败方法回调
        alert("连接失败!")
    });
}


function _touch_start(event) {
    event.preventDefault();
    $('.wenwen_text').css('background', '#c1c1c1');
    $('.wenwen_text span').css('color', '#fff');
    $('.saying').show();
}


function for_bottom() {
    var speak_height = $('.speak_box').height();
    $('.speak_box,.speak_window').animate({scrollTop: speak_height}, 500);
}

function autoWidth() {
    $('.question_text').css('max-width', $('.question').width() - 60);
}

//发送文本消息
function textMessage() {
    var text = $('#textarea').val();
    //新建消息体对象
    var obj = new RL_YTX.MsgBuilder();
    //设置自定义消息id
    var date = new Date();
    var msgid = date.getTime();
    obj.setId(msgid);
//设置发送的文本内容
    obj.setText(text);
//设置发送的消息类型1:文本消息 4:图片消息 6:压缩文件 7:非压缩文件
//发送非文本消息时，text字段将被忽略，发送文本消息时 file字段将被忽略
    obj.setType(1);
//设置接收者
    obj.setReceiver(fid);
    RL_YTX.sendMsg(obj, function () {
        sendMessage();
    }, function (obj) {//失败
        alert("发送失败!");
    }, function (sended, total) {

    });
}


//发送信息后创建界面
function sendMessage() {
    var text = $('#textarea').val();
    $('#textarea').val("");
    var str = '<div class="question">';
    str += '<div class="heard_img right"><img src="' + headImage + '"></div>';
    str += '<div class="question_text clear"><p>' + text + '</p><i></i>';
    str += '</div></div>';

    if (text == '') {
        alert('不能发送空内容');
        $('#textarea').focus();
    } else {
        $('.speak_box').append(str);
        $('#textarea').focus();
        autoWidth();
        for_bottom();
    }
}


//接受消息
function onMsgReceiveListener(obj) {
    //获取发送者为
    var sender = obj.msgSender;
//获取发送者昵称，如果不存在，使用账号代替
    var you_senderNickName = obj.senderNickName;
    var name = obj.msgSender;
    if (!!you_senderNickName) {
        name = you_senderNickName;
    }
    var content_type = null;
//获取消息版本号
    var version = obj.version;
//获取消息发送时间
    var time = obj.msgDateCreated;
//获取消息类型
//1:文本消息 2:语音消息4:图片消息6:文件
    var msgType = obj.msgType;
    if (1 == msgType || 0 == msgType) {
        //文本消息，获取消息内容
        var you_msgContent = obj.msgContent;

        createClient(you_msgContent, 1);
    } else if (2 == msgType) {
        //语音消息，获取语音文件url
        var url = obj.msgFileUrl;
    } else if (3 == msgType) {
//3：视频消息，获取视频url
        //语音消息，获取语音文件url
        var url = obj.msgFileUrl;
    } else if (4 == msgType) {
        //图片消息 获取图片url
        var url = obj.msgFileUrl;
        createClient(url, 4);

    } else {
        //后续还会支持(地理位置，视频，以及自定义消息等)
    }
}

//获得服务器消息后 创建界面
function createClient(message, code) {
    if (code == 1) {
        var ans = '<div class="answer"><div class="heard_img left"><img src="' + fheadImage + '"></div>';
        ans += '<div class="answer_text">' +
            '<p>' + message + '</p><i></i>';
        ans += '</div></div>';
        $('.speak_box').append(ans);
        for_bottom();
    }
    if (code == 4) {
        var str = '<div class="answer">' +
            '<div class="heard_img left"><img src="' + fheadImage + '"></div>' +
            '<div class="answer_text"><img src="' + message + '" style="width: 200px;height: 300px;"><i></i>' +
            '</div>';
        $('.speak_box').append(str);
        for_bottom();
    }
}

//获取参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}


/*异步上传图片*/
function uploadPhoto(layer) {
    $.ajaxFileUpload({
        url: "/multipleSave",             //需要链接到服务器地址
        secureuri: false,
        type: "post",
        fileElementId: 'uploaderInput',                         //文件选择框的id属性
        dataType: 'text',
        success: function (data, status) {
            var start = data.indexOf("{");
            var end = data.indexOf("}");
            var str = data.substring(start, end + 1);
            var result = JSON.parse(str);

            var str = '<div class="question">' +
                '<div class="heard_img right"><img src="' + headImage + '"></div>' +
                '<div class="question_text clear"><img src="' + result.data + '" style="width: 200px;height: 300px;"><i></i>' +
                '</div>';
            $('.speak_box').append(str);
            $('#textarea').focus();
            autoWidth();
            for_bottom();
            var obj = {
                "code": 2,//若是2则代表传递照片
                "from": id,
                "to": toid,
                "message": result.data
            };

            var json = JSON.stringify(obj);
            websocket.send(json);
            layer.closeAll();
        }
    });
}


//发送图片消息
function sendphotoMessage(layer) {
    var text = $('#textarea').val();
    //新建消息体对象
    var obj = new RL_YTX.MsgBuilder();
    //设置自定义消息id
    var date = new Date();
    var msgid = date.getTime();
    obj.setId(msgid);
    var file = document.getElementById("file").files[0];
    obj.setFile(file);
    obj.setType(4);
//设置接收者
    obj.setReceiver(fid);
    //消息界面创建
    var windowURL = window.URL || window.webkitURL;
    var imgUrl = windowURL.createObjectURL(document.getElementById("file").files[0]);
    var str = '<div class="question">' +
        '<div class="heard_img right"><img src="' + headImage + '"></div>' +
        '<div class="question_text clear"><img src="' + imgUrl + '" style="width: 200px;height: 300px;"><i></i>' +
        '</div>';
    $('.speak_box').append(str);
    $('#textarea').focus();
    autoWidth();
    for_bottom();
    layer.closeAll();

    RL_YTX.sendMsg(obj, function () {
        // sendMessage();

    }, function (obj) {//失败
        alert("发送失败!");
    }, function (sended, total) {

    });
}

//准备拍照
function startPhoto(layer) {
    layers = layer;
    $('#takePic').show();
    var obj = {};
    var video = document.getElementById("picshow");
    obj.tag = video;
    RL_YTX.photo.apply(obj, function (e) {
    }, function (err) {
        console.log(err);
    });
}

//开始拍照
function takePhoto() {
    var resultObj = RL_YTX.photo.make();
    //拍照成功
    if ("200" == resultObj.code) {
        //展示图片
        //发送消息
        var obj = new RL_YTX.MsgBuilder();
        var msgid = new Date().getTime();
        sendTakePhoto(msgid, resultObj.blob, 4, fid);
        $('#takePic').hide();
    }

}

//取消拍照
function cancelTakePhoto() {
    RL_YTX.photo.cancel();
    layers.closeAll();
}


//发送照片
function sendTakePhoto(msgId, file, type, receiver) {
    console.log('send Attach message: type[' + type + ']...receiver:[' + receiver + ']');
    var urls = window.URL.createObjectURL(file);
    var msgDiv = {};
    if (type == '7') {
        msgDiv["msgFileName"] = file.name;
        msgDiv["msgFileSize"] = file.size;
        msgDiv["msgFileUrl"] = urls;
    }
    msgDiv["msgFileUrl"] = urls;
    msgDiv["isSender"] = true;
    msgDiv["senderName"] = fid;
    msgDiv["msgType"] = type;
    msgDiv["chatWindow"] = fid;
    msgDiv['msgId'] = 'T' + new Date().getTime() + parseInt(Math.random() * 10000).toString();

    var obj = new RL_YTX.MsgBuilder();
    obj.setFile(file);
    obj.setType(type);
    obj.setReceiver(receiver);
    var fffff = file.name;
    var str = '<div class="question">' +
        '<div class="heard_img right"><img src="' + headImage + '"></div>' +
        '<div class="question_text clear"><img src="' + urls + '" style="width: 200px;height: 300px;"><i></i>' +
        '</div>';
    $('.speak_box').append(str);
    $('#textarea').focus();
    autoWidth();
    for_bottom();
    layers.closeAll();
    RL_YTX.sendMsg(obj, function (e) {
        //发送成功
        $('[data-msgid=' + msgDiv.msgId + ']').attr('data-msgid', e.msgClientNo);

    }, function (e) { //失败回调
        $.scojs_message(e.code + ' : ' + e.msg, $.scojs_message.TYPE_ERROR);
        $('[data-msgid=' + msgDiv.msgId + ']').addClass('msgError');
        $('[data-msgid=' + msgDiv.msgId + ']').attr('title', '发送文件失败');
        $('[data-msgid=' + msgDiv.msgId + ']').attr('data-msgid', e.msgClientNo.split('|')[1]);
    }, function (e) { //发送进度
        console.log(parseInt(e / file.size * 100) + '%');
    });
}

//发起视频聊天
function takeVideo() {
    var makeCallBuilder = new RL_YTX.MakeCallBuilder();
    makeCallBuilder.setCalled(fid);
    makeCallBuilder.setCallType(1);//呼叫的类型 0 音频 1视频
    RL_YTX.setCallView(distance, local); //呼叫类型1的时候这么传
    RL_YTX.makeCall(makeCallBuilder,
        function () {
            //呼叫成功
            // alert("呼叫成功!")
        }, function callback(obj) {
            obj.code //错误码
            alert("呼叫失败! code:", obj.code);
        })
}

//接受视频聊天
function receverVideo(obj) {
    var noticeMsg = null;
    if(obj.state == 2) { //发送请求成功
        alert("发送请求成功! currentCallId:{}"+ obj.callId)

    } else if(obj.state == 3) { //对方接受

    } else if(obj.state == 4) { //呼叫失败 对主叫设定：自动取消，对方拒绝或者忙


    } else if(obj.state == 5) { //对方挂断


    } else if(obj.state == 6) {

        var voipAcceptBuilder = new RL_YTX.AcceptCallBuilder();
        voipAcceptBuilder.setCallId(obj.callId);//请求的callId，
        voipAcceptBuilder.setCaller(uid);//请求的主叫号码，即Tony的号码

        RL_YTX.accetpCall(voipAcceptBuilder,
            function () {
                alert("接受请求")
            }, function callback(obj) {
                alert("接受失败!"+obj.code) //错误码
            })

    } else if(obj.state == 7) {
        console.log("建立呼叫");
    }






}

//发起音频聊天
function takeSound() {
    var makeCallBuilder = new RL_YTX.MakeCallBuilder();
    makeCallBuilder.setCalled(fid);
    makeCallBuilder.setCallType(0);//呼叫的类型 0 音频 1视频
    // RL_YTX.setCallView(distance, local); //呼叫类型1的时候这么传
    RL_YTX.setCallView(distance, null);//呼叫类型是0的时候这么传
    RL_YTX.makeCall(makeCallBuilder,
        function () {
            //呼叫成功
            alert("呼叫成功!")
        }, function callback(obj) {
            obj.code //错误码
            alert("呼叫失败! code:", obj.code);
        })
}
//接受音频聊天
function receverSound(obj) {
    var voipAcceptBuilder = new RL_YTX.AcceptCallBuilder();
    voipAcceptBuilder.setCallId(obj.callId);//请求的callId，
    voipAcceptBuilder.setCaller(uid);//请求的主叫号码，即Tony的号码

    RL_YTX.accetpCall(voipAcceptBuilder,
        function () {

        }, function callback(obj) {
            alert(obj.code) //错误码
        })
}